package com.sgb.kjwl.viewmodel.carrierDemand;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.transport.CarriageInfo;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CarrierDemandFtvModel extends AndroidViewModel {

    private HomeRepertory repertory;
    public ObservableField<String> messageNum = new ObservableField<>("");
    public ObservableField<GoodsSourceFilterEntity> filterEntity = new ObservableField<>(new GoodsSourceFilterEntity());
    public ObservableField<GoodsSourceLocationEntity> sendLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsSourceLocationEntity> purposeLocation = new ObservableField<>(new GoodsSourceLocationEntity());
    public ObservableField<GoodsInfoTypeEntity3> carType = new ObservableField<>(new GoodsInfoTypeEntity3());
    public ObservableField<GoodsInfoTypeEntity3> carLength = new ObservableField<>(new GoodsInfoTypeEntity3());
    public MutableLiveData<LatLng> ldLatLng = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldTypeList = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldLengthList = new MutableLiveData<>();
    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> ldAdress = new MutableLiveData();
    public MutableLiveData<ProListEntity<List<CarriageInfo>>> ldCarriageInfo = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldErrorList = new MutableLiveData();
    public String raduis;
    public int pageSize = 10;

    public String websiteNo, websiteType;

    public CarrierDemandFtvModel(Application application) {
        super(application);
    }


    /**
     * 获取列表数据（区分是否为前台主页自营页面）
     * @param context
     * @param pageNum
     */
    public void getListData(Context context, int pageNum) {
        if (!TextUtils.isEmpty(websiteNo) && !TextUtils.isEmpty(websiteType)) {
            //前台自营走老接口
            getFilterInfoList(context,pageNum);
        } else {
            getListCarFindForGoods(context,pageNum);
        }
    }

    /**
     * 获取承运信息
     *
     * @param context
     * @param pageNum
     */
    public void getFilterInfoList(Context context, int pageNum) {
        Map map = new HashMap();
        map.put("page", pageNum);
        map.put("limit", pageSize);
        if (LocationUtil.isOpenLocation(context)) {
            map.put("isAuthorization", 1);
            map.put("longitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            map.put("latitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
        } else {
            map.put("isAuthorization", 0);
            map.put("provinceNo", sendLocation.get().getProvinceNo());
        }

        if (null != filterEntity.get()) {
            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                    map.put("shipProvinceNo", "");
                } else {
                    map.put("shipProvinceNo", sendLocation.get().getProvinceNo());
                }
            }

            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                    map.put("shipCityNo", "");
                } else {
                    map.put("shipCityNo", sendLocation.get().getCityNo());
                }
            }
            if (null != sendLocation.get()) {
                if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                    map.put("shipDistrictNo", "");
                } else {
                    map.put("shipDistrictNo", sendLocation.get().getAreaNo());
                }
            }
            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                    map.put("destProvinceNo", "");
                } else {
                    map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
                }
            }

            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {
                    map.put("destCityNo", "");
                } else {
                    map.put("destCityNo", purposeLocation.get().getCityNo());
                }
            }
            if (null != purposeLocation.get()) {
                if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                    map.put("destDistrictNo", "");
                } else {
                    map.put("destDistrictNo", purposeLocation.get().getAreaNo());
                }
            }


            if (null != carLength.get()) {
                map.put("carLenNo", carLength.get().getNo());
            }


            if (!TextUtils.isEmpty(carType.get().getNo())) {
                map.put("carTypeNo", carType.get().getNo());
            }
            if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
                map.put("needVideo", "0");
            } else {
                map.put("needVideo", filterEntity.get().getNeedVideo());
            }
        }

        //前台主页--物流需求--承运需求需要传递身份no
        if (!TextUtils.isEmpty(websiteNo) && !TextUtils.isEmpty(websiteType)) {
            switch (websiteType) {
                case "0":
                    map.put("userNo", websiteNo);
                    break;
                case "1":
                    map.put("companyNo", websiteNo);
                    break;
                case "2":
                    map.put("teamNo", websiteNo);
                    break;
            }
        }

        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getFilterMapCarList(map).enqueue(new Callback<BaseEntity<ProListEntity<List<CarriageInfo>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Response<BaseEntity<ProListEntity<List<CarriageInfo>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() == null) {
                        MToast.showToast(context, "暂无数据");
                        return;
                    }
                    if (response.body().getData().getList() == null) {
                        MToast.showToast(context, "暂无数据");
                        return;
                    }
                    Log.v("sourceList", response.body().getData().getList().toString());
                    ldCarriageInfo.postValue(response.body().getData());
                } else {
                    ldErrorList.postValue(true);
                    if (TextUtils.isEmpty(response.body().getMsg())) {
                        MToast.showToast(context, response.body().getState());
                    } else {
                        MToast.showToast(context, response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                t.printStackTrace();
                MToast.showToast(context, t.getMessage());
            }
        });

    }


    public void getAddressModel() {
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {

                if (data != null && data.size() > 0) {
                    ldAdress.postValue(data);
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {

            }
        });
    }


    /**
     * 根据城市区域查询经纬度
     *
     * @param context
     * @param cityName
     * @param areaName
     */
    public void getLocation(Context context, String cityName, String areaName) {
        if (TextUtils.isEmpty(cityName) || cityName.equals("不限")) {
            cityName = sendLocation.get().getProvinceName();
        }
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int code) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
                if (code != 1000) return;
                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                        geocodeResult.getGeocodeAddressList().size() > 0) {
                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                    double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                    double longitude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                    //回调UI
                    ldLatLng.postValue(new LatLng(latitude, longitude));
                } else {
                    MToast.showToast(getApplication(), "地址名出错");
                }
            }
        });
        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName + areaName, cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }


    /**
     * 获取车辆类型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                List<GoodsInfoTypeEntity3> carTypeList = data.getData() != null ? data.getData() : new ArrayList<>();
                List<GoodsInfoTypeEntity3> carLenList = new ArrayList<>();
                //添加全部车长数据
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) continue;
                    carLenList.addAll(carType.getCarLenList());
                }
                //添加车型不限时所有车长数据
                GoodsInfoTypeEntity3 type = new GoodsInfoTypeEntity3("", "不限");
                type.setCarLenList(carLenList);
                carTypeList.add(0, type);
                //添加子列表不限车长
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) {
                        carType.setCarLenList(new ArrayList<>());
                    }
                    GoodsInfoTypeEntity3 len = new GoodsInfoTypeEntity3("", "不限");
                    carType.getCarLenList().add(0, len);
                }
                //刷新车长与车型
                ldTypeList.postValue(carTypeList);
                ldLengthList.postValue(carLenList);
            }
        });
    }

    public void getListCarFindForGoods(Context context, int pageNum) {
        Map map = new HashMap();
        map.put("page", pageNum);
        map.put("limit", pageSize);
        if (LocationUtil.isOpenLocation(context)) {
            map.put("longitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
            map.put("latitude", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
        } else {
            // TODO: 2021/12/15 没开启定位逻辑处理

        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getProvinceNo())) {
                map.put("provinceNo", "");
            } else {
                map.put("provinceNo", sendLocation.get().getProvinceNo());
            }
        }

        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getCityNo())) {
                map.put("cityNo", "");
            } else {
                map.put("cityNo", sendLocation.get().getCityNo());
            }
        }
        if (null != sendLocation.get()) {
            if (TextUtils.isEmpty(sendLocation.get().getAreaNo())) {
                map.put("districtNo", "");
            } else {
                map.put("districtNo", sendLocation.get().getAreaNo());
            }
        }
        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getProvinceNo())) {
                map.put("destProvinceNo", "");
            } else {
                map.put("destProvinceNo", purposeLocation.get().getProvinceNo());
            }
        }

        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getCityNo())) {
                map.put("destCityNo", "");
            } else {
                map.put("destCityNo", purposeLocation.get().getCityNo());
            }
        }
        if (null != purposeLocation.get()) {
            if (TextUtils.isEmpty(purposeLocation.get().getAreaNo())) {
                map.put("destDistrictNo", "");
            } else {
                map.put("destDistrictNo", purposeLocation.get().getAreaNo());
            }
        }

        if (null != carLength.get()) {
            map.put("carLenNo", carLength.get().getNo());
        }

        if (!TextUtils.isEmpty(carType.get().getNo())) {
            map.put("carTypeNo", carType.get().getNo());
        }

        if (TextUtils.isEmpty(filterEntity.get().getNeedVideo())) {
            map.put("needVideo", "0");
        } else {
            map.put("needVideo", filterEntity.get().getNeedVideo());
        }

        NewAPIManager.getInstance().getLogisticsAPI().getListCarFindForGoods(map).enqueue(new Callback<BaseEntity<ProListEntity<List<CarriageInfo>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Response<BaseEntity<ProListEntity<List<CarriageInfo>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() == null || response.body().getData().getList() == null) {
                        MToast.showToast(context, "暂无数据");
                    } else {
                        ldCarriageInfo.postValue(response.body().getData());
                    }
                } else {
                    ldErrorList.postValue(true);
                    if (TextUtils.isEmpty(response.body().getMsg())) {
                        MToast.showToast(context, response.body().getState());
                    } else {
                        MToast.showToast(context, response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<CarriageInfo>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                t.printStackTrace();
                MToast.showToast(context, t.getMessage());
            }
        });
    }

}
